Single Number III

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Note:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

Solution:

  1. public class Solution {
  2. public int[] singleNumber(int[] nums) {
  3. int xor = 0, a = 0, b = 0;
  4. for (int i = 0; i < nums.length; i++)
  5. xor ^= nums[i];
  6. // Get its last set bit
  7. xor &= -xor;
  8. //xor = xor & ~ (xor - 1);
  9. for (int i = 0; i < nums.length; i++) {
  10. if ((xor & nums[i]) != 0)
  11. a ^= nums[i];
  12. else
  13. b ^= nums[i];
  14. }
  15. return new int[]{a, b};
  16. }
  17. }